const mongoose = require('mongoose');
const User = require('../model/user.model');

/*新增*/
exports.create = function(req, res, next) {
    const user = new User(req.body); //请求方式为post

    user.save().then(data => {
        res.json(data);
    });
}

/*修改*/
exports.update = function(req, res, next) {
    const id = req.params.id;
    const user = new User(req.body);
    User.findByIdAndUpdate(id, { $set: req.body }, { new: false })
        .then(data => {
            res.json(data); //返回的data是修改前的数据
        });
}
exports.get = function(req, res, next) {
    const id = req.params.id;
    User.findById(id, function(err, data) {
        res.json(data)
    })
}

/*删除*/
exports.remove = function(req, res, next) {
    const id = req.params.id;
    User.findByIdAndRemove(id, function(err, data) {
        res.json({ "message": "删除成功" });
    });
}

/*删除多个*/
exports.removes = function(req, res, next) {
    var ids = req.body.ids;
    ids = ids.split(',');
    if (ids.length > 0) {
        User.remove({ _id: { $in: ids } })
            .then(data => {
                res.json({ "message": "删除成功" });
            });
    } else {
        res.status(404).send({ "message": "没有选中记录" })
    }
}

/*查找*/
exports.list = function(req, res, next) {
    var page = req.body.page || 1;
    var limit = req.body.rows || 5;

    var queryCondition = {};

    if (req.body.name && req.body.name.trim().length > 0) {
        name = req.body.name;
        queryCondition = {
            "username": new RegExp(name, "i")
        }
    }

    User.paginate(queryCondition, { page: +page, limit: +limit }, function(err, result) {
        var rows = result.docs;
        result.rows = rows;
        delete result.docs;
        res.json(result);
    });
}